﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Models;

public partial class Admin_User_OrderList : System.Web.UI.Page
{
    public string OCount = "1";
    private string type = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.Params["type"]))
        {
            type = HttpContext.Current.Request.QueryString["type"];

        }
        if(!IsPostBack)
        grdbind();
    }

    public void grdbind()
    {
        using (Entities bll = new Entities())
        {
            var Bpl = from p in bll.T_OrderInfo.OrderByDescending(p => p.NId) select p;

            //if (ddlState.SelectedValue != "请选择")
            //{
            //    int type = int.Parse(ddlState.SelectedValue);
            //    Bpl = Bpl.Where(p => p.NState == type);
            //}
            if (ddlPayState.SelectedValue != "请选择")
            {
                int type = int.Parse(ddlPayState.SelectedValue);
                Bpl = Bpl.Where(p => p.NPayState == type);

            }

            //时间查询
            //业务逻辑：如果选择了两个时间，则按时间段查询，否则按单个时间查询
            if (!string.IsNullOrEmpty(txtStartTime.Text.Trim()) && !string.IsNullOrEmpty(txtEndtime.Text.Trim()))//按时间段查询
            {
                DateTime starttime = Convert.ToDateTime(txtStartTime.Text.Trim());
                DateTime endtime = Convert.ToDateTime(txtEndtime.Text.Trim());
                Bpl = Bpl.Where(p => p.DCreatDate > starttime && p.DCreatDate <= endtime);
            }
            else //根据单个时间查询
            {
                if (!string.IsNullOrEmpty(txtStartTime.Text.Trim()))
                {
                    DateTime startime = Convert.ToDateTime(txtStartTime.Text.Trim());
                    Bpl = Bpl.Where(p => p.DCreatDate == startime);
                }
                else if ((!string.IsNullOrEmpty(txtEndtime.Text.Trim())))
                {
                    DateTime endtime = Convert.ToDateTime(txtEndtime.Text.Trim());
                    Bpl = Bpl.Where(p => p.DCreatDate == endtime);
                }
            }
            //根据订单号
            if (!string.IsNullOrEmpty(txtOrder.Text.Trim()))
            {
                int _OID = int.Parse(txtOrder.Text.Trim().ToString());
                Bpl = Bpl.Where(p => p.NId == _OID);
            }

            if (!string.IsNullOrEmpty(txtSHUtel.Text.Trim()))
            {
              
                Bpl = Bpl.Where(p => p.Utel.Contains(txtSHUtel.Text.Trim()) || p.UyuyueName.Contains(txtSHUtel.Text.Trim()));
            }


            if (txtUtel.Text.Trim() != "")
            {
                var user = bll.User.FirstOrDefault(p => p.UTrueName.Contains(txtUtel.Text.Trim()) || p.UNickName.Contains(txtUtel.Text.Trim()) || p.UTel == txtUtel.Text.Trim());
                if (user != null)
                {
                    Bpl = Bpl.Where(p => p.Uopenid == user.UGuid);
                }
            }

            //if (!string.IsNullOrEmpty(txtUtel.Text.Trim()))
            //{

            //    Bpl = Bpl.Where(p => p.OrderID == txtUtel.Text.Trim());
            //}




            AspNetPager1.RecordCount = Bpl.Count(); 
            this.rptList.DataSource = Bpl.Skip((AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize).Take(AspNetPager1.PageSize).ToList();  //这里好像一定要Tolist();不然会有点错误;
            this.rptList.DataBind();
        }
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        grdbind();
    }



    protected void btnSearch_Click(object sender, EventArgs e)
    {
        grdbind();
    }

    protected void ddlStore_SelectedIndexChanged(object sender, EventArgs e)
    {
        grdbind();
    }


    public string getPayState(string OPayState)
    {
        string Result = "";
       
        if (OPayState != "")
        {
            Result = "<div style=\"padding:1px 1px;font-size:12px;line-height:1.5;border-radius: 3px;color: #23c6c8;text-align:center;\">已支付</div>";
        }
        else
        {
            Result = "<div style=\"padding: 1px 1px;font-size:12px;line-height:1.5;border-radius: 3px;color:#ed5565;text-align:center;\">未支付</div>";
        }
        return Result;
    }
    public string getFahuoState(string OState)
    {
        string Result = "";
        if (OState != "")
        { 
 
        int state = int.Parse(OState);
        switch (state)
        {

            case -4: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color:#333;; border-color:##ed5565;;color:#FFFFFF;text-align:center;\">系统作废</div>"; break;
            case -3: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color:#333;; border-color:##ed5565;;color:#FFFFFF;text-align:center;\">后台作废</div>"; break;
            case -2: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color:#333;; border-color:##ed5565;;color:#FFFFFF;text-align:center;\">用户取消</div>"; break;
            case  0: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color:#333;; border-color:##ed5565;;color:#FFFFFF;text-align:center;\">待支付</div>"; break;
            case  1: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color:#ed5565;; border-color:##ed5565;;color:#FFFFFF;text-align:center;\">正常订单</div>"; break;
			case  2: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color: #23c6c8; border - color: #23c6c8;color: #FFFFFF;text-align:center;\">已发货</div>"; break;
			case  3: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color: #23c6c8; border - color: #23c6c8;color: #FFFFFF;text-align:center;\">已验收</div>"; break;
			case  4: Result = "<div style=\"padding:1px;margin: 5px 0;font-size:12px;line-height:1.5;border-radius:3px;background-color: #23c6c8; border - color: #23c6c8;color: #FFFFFF;text-align:center;\">已评价</div>"; break;
        }
        }
        return Result;
    }

    public string getParentTel(string opID)
    {

        Entities db = new Entities();

        string result = "";
        var LU = db.User.FirstOrDefault(p => p.UGuid == opID);
        if (LU != null)
        {
            var LU_UP = db.User.FirstOrDefault(p => p.UGuid == LU.UGuid);
            if (LU_UP != null)
            {
                result = LU.UTel;
            }        }
        return result;

    }

    /// <summary>
    /// 导出Excel
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// AddExcelHead();AddExcelbottom();解决导出的excel无表格线
    /// 本质上并非标准的excel格式，是把html格式的文件另存为excel的格式，然后用excel打开
    protected void btnExcel_Click(object sender, EventArgs e)
    {
        Button Btn = sender as Button;
        string commandArgument = Btn.CommandArgument.ToString();
        using (Entities bll = new Entities())
        {
            var whereOR = PredicateBuilder.False<S_Order>();
            string allids = HiddenField1.Value;
            if (allids.Length>0)
            {   
            string[] allidss = allids.Remove(allids.Length - 1).Split('-');
            foreach (var item in allidss)
               {
                int orid=int.Parse(item);
                whereOR = whereOR.Or(c => c.OrderID == orid);   
               }
            }
            var Bpl = bll.S_Order.Where(whereOR.Compile());
            StringBuilder sbExcel = new StringBuilder();
            AddExcelHead(sbExcel);
            int i = 1;
            string xlsname = "";


            DateTime dachutime = DateTime.Now;


            if (commandArgument == "goods")
            {
                xlsname = "货单信息表.xls";
                sbExcel.AppendLine("<table border=\"1\">");
                sbExcel.Append("<tr>");
                sbExcel.Append("<td>订单号</td>");
                sbExcel.Append("<td>商品名称</td>");
                sbExcel.Append("<td>商品数量</td>");
                sbExcel.Append("<td>客户姓名</td>");
                sbExcel.Append("<td>客户电话</td>");
                sbExcel.Append("</tr>");
                foreach (var item in Bpl)
                {
                    sbExcel.Append("<tr>");
                    sbExcel.Append("<td style=\"vnd.ms-excel.numberformat:@\">" + item.OrderID + "</td>");
                    sbExcel.Append("<td>" + getallgname(item.OrderID) + "</td>");
                    sbExcel.Append("<td style=\"vnd.ms-excel.numberformat:@\">" + getallOnumber(item.OrderID) + "</td>");
                    sbExcel.Append("<td>" + item.OPeople + "</td>");
                    sbExcel.Append("<td>" + item.OTel + "</td>");
                     sbExcel.Append("<td>" + getexcelPayState((int)item.OPayState) + "</td>");
                    sbExcel.Append("</tr>");
                    i++;
                    item.OendTime = dachutime;

                }
                bll.SaveChanges();
                sbExcel.AppendLine("</table");
            }
            if (commandArgument == "post")
            {
                xlsname = "物流信息表.xls";
                sbExcel.AppendLine("<table border=\"1\">");
                sbExcel.Append("<tr>");
                sbExcel.Append("<td>订单号</td>");
                sbExcel.Append("<td>收件地址</td>");
                sbExcel.Append("<td>电话</td>");
                sbExcel.Append("<td>收件人</td>");
                sbExcel.Append("</tr>");
                foreach (var item in Bpl)
                {
                    sbExcel.Append("<tr>");
                    sbExcel.Append("<td style=\"vnd.ms-excel.numberformat:@\">" + item.OrderID + "</td>");
                    sbExcel.Append("<td>"+ item.OProvance + item.OCity + item.ODistrict + item.OAddress + "</td>");
                    sbExcel.Append("<td style=\"vnd.ms-excel.numberformat:@\">" + item.OTel + "</td>");
                    sbExcel.Append("<td>" + item.OPeople + "</td>");
                    sbExcel.Append("</tr>");
                    i++;
                    item.OendTime = dachutime;
                }
                bll.SaveChanges();
            }
            AddExcelbottom(sbExcel);
            byte[] Exc = Encoding.Default.GetBytes(sbExcel.ToString());
            MemoryStream ms = new MemoryStream(Exc);
            BinaryReader br = new BinaryReader(ms);
            Exc = ms.ToArray();
            Response.AddHeader("Accept-Ranges", "bytes");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(xlsname));
            Response.BinaryWrite(Exc);
            Response.End();

    
        }
    }
    protected string getallgname(int order_id)
    {
        string xxx="";
            if (order_id != 0)
            {
              using (Entities MyDB = new Entities()) 
            { 
                var mnews = MyDB.S_Order.Where(x => x.OParentId == order_id || x.OrderID == order_id);//全部
                foreach (var myorder in mnews)
                    xxx += myorder.SPName+"x("+myorder.ONumber+")" + "<br style='mso-data-placement:same-cell;'/>";
            }
        }
        return xxx;     
    }
    protected string getallOnumber(int order_id)
    {
        string xxx = "";
        if (order_id != 0)
        {
            using (Entities MyDB = new Entities())
            {
                xxx= MyDB.S_Order.Where(x => x.OParentId == order_id || x.OrderID == order_id).Sum(x=>x.ONumber).ToString();//全部
  
            }
        }
        return xxx;
    }


    public string getRoom(string id)
    {
        string Result;
        int _id = Convert.ToInt32(id);
        using (Entities MyDB = new Entities())
        {
            var xx = MyDB.S_Store_Item.SingleOrDefault(x => x.SItemID == _id);//全部
            Result = xx.Sname.ToString();//全部

        }
        return Result;
    }

    public string getUser(string id)
    {
        string Result= id;

        //using (Entities MyDB = new Entities())
        //{
        //    var xx = MyDB.User.SingleOrDefault(x => x.SItemID == _id);//全部
        //    Result = xx.Sname.ToString();//全部

        //}
        return Result;
    }
    


    public string getexcelPayState(int state)
    {
        string Result;
        if (state == 1)
        {
            Result = "邮费已支付";
        }
        else
        {
            Result = "邮费未支付";
        }
        return Result;
    }

    protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {   //当页面页数改变时，执行这个方法；
        AspNetPager1.CurrentPageIndex = e.NewPageIndex;
        grdbind();
    }
    protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int id = Convert.ToInt32(((Label)e.Item.FindControl("lb_id")).Text);
        Entities bll = new Entities();
        S_Order model = bll.S_Order.First(p => p.OrderID == id);
        switch (e.CommandName.ToLower())
        {
            case "del":
                bll.S_Order.Remove(model);
                break;
        }
        bll.SaveChanges();
        grdbind();
    }





    protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
     
    }

    /// <summary>
    /// Excel头部
    /// </summary>
    /// <returns></returns>
    public static void AddExcelHead(StringBuilder sb)
    {
        //StringBuilder sb = new StringBuilder();
        sb.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
        sb.Append(" <head>");
        sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
        sb.Append(" <!--[if gte mso 9]><xml>");
        sb.Append("<x:ExcelWorkbook>");
        sb.Append("<x:ExcelWorksheets>");
        sb.Append("<x:ExcelWorksheet>");
        sb.Append("<x:Name></x:Name>");
        sb.Append("<x:WorksheetOptions>");
        sb.Append("<x:Print>");
        sb.Append("<x:ValidPrinterInfo />");
        sb.Append(" </x:Print>");
        sb.Append("</x:WorksheetOptions>");
        sb.Append("</x:ExcelWorksheet>");
        sb.Append("</x:ExcelWorksheets>");
        sb.Append("</x:ExcelWorkbook>");
        sb.Append("</xml>");
        sb.Append("<![endif]-->");
        sb.Append(" </head>");
        sb.Append("<body>");
        //return sb.ToString();
    }

    /// <summary>
    /// Excel尾部
    /// </summary>
    /// <returns></returns>
    public static void AddExcelbottom(StringBuilder sb)
    {
        //StringBuilder sb = new StringBuilder();
        sb.Append("</body>");
        sb.Append("</html>");
        //return sb.ToString();
    }
}